package com.itCar.base.tools;

import com.itCar.base.config.exceptionhandler.BizException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @ClassName: FileUtils
 * @Description: TODO
 * @author: liuzg
 * @Date: 2022/8/17 9:56
 * @Week: 星期三
 * @Version: v1.0
 */
public class FileUtils {

    private static String separator = "";

    @Value("${config.fi.temporarySaveFilePath}")
    private static String temporarySaveFilePath;

    // 获取当前系统环境 文件的分隔符 win // linux \
    public static String getSeparator() {
        separator = File.separator;
        return File.separator;
    }

    public static String checkFile(MultipartFile file){
        if (file.isEmpty()) {
            throw new BizException("文件未找到");
        }
        String path = FileUtils.uploadFile(file);
        return path;
    }

    /**
     * 上传文件指定位置
     *
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file) {
        String name = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String savePath = temporarySaveFilePath + name;
        // 保存文件的文件夹
        File folder = new File(savePath);
        // 判断路径是否存在,不存在则自动创建
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            file.transferTo(folder);
        } catch (IOException e) {
            throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件上传失败");
        }
        return savePath;
    }

    // 测试文件删除（文件：只删除文件、文件夹：删除文件夹下所有文件和文件夹）
    public static void main(String[] args) {
        delFolder("D:\\1\\2\\新建文本文档.txt");
    }

    /**
     * 删除文件
     *
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除指定位置文件
     *
     * @param path
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            // 递归调用
            if (temp.isDirectory()) {
                delAllFile(path + File.separator + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + File.separator + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }


    /**
     * 根据路径删除文件
     *
     * @param filePath
     * @return
     */
    public static boolean delFile(String filePath) {
        boolean flag = true;
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                return flag;
            }
            return false;
        }
        return false;
    }

    /**
     * 异步删除
     *
     * @param path
     */
    public static void asyncDel(String path) {
        // 采用异步删除文件
        new Thread(() -> {
            System.out.println("异步删除临时文件线程 =====> 开始 =====> " + DateUtil.getDate(0));
            boolean delFile = delFile(path);
            if (delFile) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
            System.out.println("异步删除临时文件线程 =====> 结束 =====> " + DateUtil.getDate(0));
        }).start();
    }

    /**
     * 读取文件内容为二进制数组
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] read(String filePath) throws IOException {

        InputStream in = new FileInputStream(filePath);
        byte[] data = inputStream2ByteArray(in);
        in.close();

        return data;
    }

    /**
     * 流转二进制数组
     *
     * @param in
     * @return
     * @throws IOException
     */
    static byte[] inputStream2ByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /**
     * 保存文件
     *
     * @param filePath
     * @param fileName
     * @param content
     */
    public static void save(String filePath, String fileName, byte[] content) {
        try {
            File filedir = new File(filePath);
            if (!filedir.exists()) {
                filedir.mkdirs();
            }
            File file = new File(filedir, fileName);
            OutputStream os = new FileOutputStream(file);
            os.write(content, 0, content.length);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
